/*
 * @Author: wuqingchun
 * @Date: 2024-04-17 16:54:55
 * @Description: 文件映射
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-04-18 10:57:23
 */
#ifndef __MMAP_FILE_H__
#define __MMAP_FILE_H__

#include <cstdio>
#include <cstring>
#include <cerrno>
#include <cstdlib>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>

class MMapFile
{
private:
    /* data */
public:
    MMapFile(/* args */)
    {

    }

    ~MMapFile()
    {
        Close();
    }

    int Open(const char* pcFileName, size_t ulSize)
    {
        int iFd = open(pcFileName, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);
        if (iFd == -1)
        {
            printf("%s\n", strerror(errno));
            return -1;
        }

        int iErr = ftruncate(iFd, ulSize);
        if (iErr != 0)
        {
            printf("ftruncate error, %s\n", strerror(errno));
            (void)close(iFd);
            return -1;
        }
        
        // 将文件映射到当前内存
        setenv("HUGETLB_PAGESIZE", "2097152", 1);
        //void* m_pMemStart = mmap(NULL, ulSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS|MAP_HUGETLB, -1, 0);
        void* m_pMemStart = mmap(NULL, ulSize, PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS | MAP_HUGETLB, -1, 0);
        if (m_pMemStart == MAP_FAILED)
        {
            printf("mmap error, %s\n", strerror(errno));
            (void)close(iFd);
            return -1;
        }

        //*(int*)m_pMemStart = 100;

        // 关闭文件描述符不影响内存映射？？
        close(iFd);
        m_ulFileSize = ulSize;
        m_iFd = iFd;

        return 0;
    }

    void Close()
    {
        if (m_iFd != -1)
        {
            close(m_iFd);
            m_iFd = -1;
        }

        if (m_pMemStart != nullptr)
        {
            (void)munmap(m_pMemStart, m_ulFileSize);
            m_pMemStart = nullptr;
            m_ulFileSize = 0;
        }
    }
private:
    int m_iFd = -1;
    size_t m_ulFileSize = 0;
    void* m_pMemStart = nullptr;
};

#endif //__MMAP_FILE_H__
